public class MaxAreaOfIsland {
    int max = 0;

    public int maxAreaOfIsland(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int ans = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    infer(grid, i, j, n, m);
                    ans = Math.max(ans, max);
                    max = 0;
                }
            }
        }
        return ans;
    }

    public void infer(int[][] grid, int i, int j, int n, int m) {
        if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0 || grid[i][j] == 2) {
            return;
        } else {
            grid[i][j] = 2;
            max++;
        }
        infer(grid, i - 1, j, n, m);
        infer(grid, i + 1, j, n, m);
        infer(grid, i, j - 1, n, m);
        infer(grid, i, j + 1, n, m);
    }
}
